// cppjieba_lua.cpp
#include "cppjieba/Jieba.hpp"
#include <vector>
#include <string>
#include <sstream>
#include <cstring>

#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif

static cppjieba::Jieba *jieba = nullptr;

extern "C" {

// 初始化 Jieba
EXPORT void jieba_init(const char* dict_path,
                       const char* hmm_path,
                       const char* user_path,
                       const char* idf_path,
                       const char* stop_words_path)
{
    if (!jieba) {
        jieba = new cppjieba::Jieba(dict_path, hmm_path, user_path, idf_path, stop_words_path);
    }
}

// 分词函数
// 输入 text，返回以空格分隔的字符串
EXPORT const char* jieba_cut(const char* text)
{
    static std::string result; // 返回给 Lua
    if (!jieba) return "";

    std::vector<std::string> words;
    jieba->Cut(text, words, true);

    std::ostringstream oss;
    for (size_t i = 0; i < words.size(); i++) {
        if (i != 0) oss << " ";
        oss << words[i];
    }
    result = oss.str();
    return result.c_str();
}

} // extern "C"
